package com.learn.transaction_control.third_beans;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @EnableTransactionManagement：事务管理器，默认从Spring容器中寻找名为jdbcTransactionManager的Bean。不同的框架所需的数据源不同
 */
@Component
@EnableTransactionManagement
public class ThirdBeans {
    @Bean
    public DruidDataSource dataSource(
            @Value("${my-app.driver}") String driverClassName,
            @Value("${my-app.url}") String url,
            @Value("${my-app.username}") String username,
            @Value("${my-app.password}") String password
    ) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    
    @Bean
    public JdbcTemplate jdbcTemplate(DruidDataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
    
    @Bean
    public DataSourceTransactionManager jdbcTransactionManager(DruidDataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
